from django.shortcuts import render, HttpResponse, redirect
from bookapp import models
from .models import Ebook
import requests
from lxml import etree

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
}


# Create your views here.
def index(request):
    return redirect('/admin/message/')


def account(request):
    book_data = models.Ebook.objects.all()
    return render(request, 'account.html', {"book_data": book_data})


def message(request):
    if request.method == "POST":
        # 获取输入框链接爬取数据
        net = request.POST.get("net")
        for i in range(10):
            link = net + "?start=" + str(i * 25)
            get_book(link)
    book_data = models.Ebook.objects.all()
    return render(request, 'message.html', {"book_data": book_data})


def comment(request):
    return render(request, 'comment.html')


def add(request):
    return render(request, 'book_add.html')


# 爬取豆瓣读书的数据
def get_book(url):
    response = requests.get(url, headers=headers)
    html = etree.HTML(response.text)
    books = html.xpath('//tr[@class="item"]')
    comment = []
    for book in books:
        comment_ = book.xpath('td/p[2]/span/text()')
        comment.append(comment_[0] if len(comment_) != 0 else ' ')
    book_nums = []
    book_nums_ = html.xpath('//div[@class="pl2"]/a/@href')
    for i in book_nums_:
        data = i.split('/')
        book_nums.append(data[-2])
    book_name = html.xpath('//div[@class="pl2"]/a/@title')
    rating_nums = html.xpath('//span[@class="rating_nums"]/text()')
    rating_people_ = html.xpath('//span[@class="pl"]/text()')
    rating_people = []
    for i in rating_people_:
        rating_people.append(i.strip('()\n 人评价'))
    book_infos = html.xpath('//p[@class="pl"]/text()')
    autor = []
    translator = []
    publisher = []
    publisher_data = []
    price = []
    for j in book_infos:
        data = j.split('/')
        autor.append(data[0])
        translator.append(data[1] if len(data) == 5 else ' ')
        publisher.append(data[-3])
        publisher_data.append(data[-2])
        price.append(data[-1])
    book_data = []
    for i in range(25):
        book = Ebook(
            book_name=book_name[i],
            autor=autor[i],
            translator=translator[i],
            publisher=publisher[i],
            publisher_data=publisher_data[i],
            price=price[i],
            rating_nums=rating_nums[i],
            rating_people=rating_people[i],
            comment=comment[i],
            book_num=book_nums[i],
        )
        book_data.append(book)

    # 将书籍数据保存到数据库
    Ebook.objects.bulk_create(book_data)
